package com.vilynn.learning.tree;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Created by wangweilin on 2018/10/27.
 */
@Data
@NoArgsConstructor
public class SimpleTree<T> {
    private T data;
    private int height;
    private SimpleTree<T> root;
    private SimpleTree<T> left;
    private SimpleTree<T> right;

    public SimpleTree(T data) {
        this.data = data;
    }

    public void add(T data) {
        if(root == null){
            root = new SimpleTree<>(data);
            return;
        }

        SimpleTree simpleTree = root;
        do{
            if(height(root.left) < height(root.right)){
                add(data, root.right);
            }if(height(root.left) > height(root.right)){
                add(data, root.right);
            }

        }while (simpleTree != null);
    }

    private void add(T data, SimpleTree<T> tree) {
        if(tree.left == null){
            tree.setLeft(new SimpleTree<>(data));
        }else if(tree.right == null){
            tree.setRight(new SimpleTree<>(data));
        }
    }

    private int height(SimpleTree<T> tree) {
        return tree == null ? -1 : tree.height;
    }

    public int depth(SimpleTree<T> node) {
        if (node == null) {
            return 0;
        }

        int l = depth(node.getLeft());
        int r = depth(node.getRight());
        if (l > r) {
            return l + 1;
        } else {
            return r + 1;
        }
    }

    public void print() {
        boolean firstLeft = true;
        do{
            if(root != null){
                System.out.println(root.getData() + "-");
                if(root.getLeft() != null){
                    System.out.print(root.getLeft().getData() + "-");
                }
                if(root.getRight() != null){
                    System.out.println(root.getRight().getData() + "-");
                }
            }
            if(firstLeft){
                root = root.getLeft();
                firstLeft = false;
            }else{
                root = root.getRight();
                firstLeft = true;
            }
        }while (root != null);
    }

}
